<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>钉钉</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="format-detection" content="telephone=no, email=no" />
		<!--标准mui.css-->
		<link rel="stylesheet" href="./css/mui.min.css">
		<!--App自定义的css-->
		<link rel="stylesheet" type="text/css" href="./css/app.css" />
		<link rel="stylesheet" href="./css/mui.indexedlist.css" />
		<link rel="stylesheet" href="./style/main.css" />
		<link rel="shortcut icon" href="favicon.ico" />
		<style>
			#clipArea {
				/* margin: 20px; */
				height: 300px;
			}
			#view {
				margin: 0 auto;
				width: 200px;
				height: 200px;
				border-radius: 5px;
			}
		</style>
	</head>

	<body  ontouchstart="">
		<!--标题-->
		<header class="mui-bar mui-bar-nav">
			<!--<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>-->
			<h1 class="mui-title page-title"><img src="./img/logo.png" class="logo"/><span>钉钉</span></h1>
		</header>

		<!--底部导航-->
		<nav class="mui-bar mui-bar-tab">
			<a class="mui-tab-item mui-active" href="javascript:;" tap="tabbar">
				<span class="mui-icon mui-icon-home"></span>
				<span class="mui-tab-label">首页</span>
			</a>
			<a class="mui-tab-item" href="javascript:;" tap="tabbar-with-chat">
				<span class="mui-icon mui-icon-email"><span class="mui-badge" id="badge"></span></span>
				<span class="mui-tab-label">消息</span>
			</a>
			<a class="mui-tab-item" href="javascript:;" tap="tabbar-with-contact">
				<span class="mui-icon mui-icon-contact"></span>
				<span class="mui-tab-label">通讯录</span>
			</a>
			<a class="mui-tab-item" href="javascript:;" tap="tabbar-with-map">
				<span class="mui-icon mui-icon-gear"></span>
				<span class="mui-tab-label">设置</span>
			</a>
		</nav>

		<!--内容区域-->
		<div class="mui-content">
			<!--首页-->
			<div id="tabbar" class="mui-control-content mui-active">
				<div class="title"><span>早上好,今天请继续加油</span></div>
			</div>
			<!--消息列表-->
			<div id="tabbar-with-chat" class="mui-control-content">
				<ul class="mui-table-view" id="messageList">
				</ul>
			</div>
			<!--联系人列表-->
			<div id="tabbar-with-contact" class="mui-control-content">
				<div id="list" class="mui-indexed-list" style="height: 623px;">
				<div class="mui-indexed-list-inner" style="height: 588px;">
					<div class="mui-indexed-list-empty-alert">没有数据</div>
					<ul class="mui-table-view  mui-transitioning" id="contact">
					</ul>
				</div>
			</div>
			</div>
			<!--个人设置-->
			<div id="tabbar-with-map" class="mui-control-content">
				<ul class="mui-table-view mui-table-view-chevron" style="margin: 25px 0;">
					<li class="mui-table-view-cell mui-media">
						<a class="mui-navigate-right" id="showAccount">
							<img class="mui-media-object mui-pull-left head-img" id="myphoto" src="./img/photo.jpg">
							<div class="mui-media-body">
								<span id="mynickname"></span>
								<p class="mui-ellipsis">账号: <span id="myusername"></span> </p>
							</div>
						</a>
					</li>
				</ul>
				<ul class="mui-table-view">
					<li class="mui-table-view-cell">
						<a class="mui-navigate-right">
							新消息通知
						</a>
					</li>
					<li class="mui-table-view-cell">
						<a class="mui-navigate-right">
							隐私
						</a>
					</li>
					<li class="mui-table-view-cell">
						<a class="mui-navigate-right">
							通用
						</a>
					</li>
				</ul>
				<ul class="mui-table-view" style="margin-top: 25px;">
					<li class="mui-table-view-cell">
						<a class="mui-navigate-right">
							关于钉钉
						</a>
					</li>
				</ul>
				<ul class="mui-table-view" style="margin-top: 25px;">
					<li class="mui-table-view-cell">
						<a style="text-align: center;color: #FF3B30;" id="logout" tap="login">
							退出<span class="mui-tab-label">登录</span>
						</a>
					</li>
				</ul>
			</div>

			<!--登录-->
			<div id="login" class="mui-control-content">
				<form class="mui-input-group" style="margin-top: 25px;">
					<div class="mui-input-row">
						<label>账号</label>
						<input type="text" placeholder="请输入账号" id="l_username">
					</div>
					<div class="mui-input-row mui-password">
						<label>密码</label>
						<input type="password" class="mui-input-password" placeholder="请输入密码" id="l_password">
					</div>
				</form>
				<ul class="mui-table-view" style="margin-top: 25px;">
					<li class="mui-table-view-cell">
						<span>自动登录</span>
						<div class="mui-switch mui-active">
						  <div class="mui-switch-handle"></div>
						</div>
					</li>
				</ul>
				<div class="mui-button-row" style="margin: 25px auto;width: 98%;">
						<button type="button" style="padding:10px 0;height: 100%;;" class="mui-btn mui-btn-royal mui-btn-block" id="loginBtn">确认</button>&nbsp;&nbsp;
						<button type="button" style="padding:10px 0;height: 100%;;" class="mui-btn mui-btn-warning mui-btn-block" id="signUp" tap="register">立即<span class="mui-tab-label">注册</span></button>&nbsp;&nbsp;
				</div>
			</div>


			<!-- 注册Panel -->
			<div id="register" class="mui-control-content">
				<form class="mui-input-group" style="margin-top: 25px;">
					<div class="mui-input-row">
						<label>账号</label>
						<input type="text" placeholder="请输入账号" id="r_username">
					</div>
					<div class="mui-input-row mui-password">
						<label>密码</label>
						<input type="password" class="mui-input-password" placeholder="请输入密码" id="r_password">
					</div>
					<div class="mui-input-row">
						<label>昵称</label>
						<input type="text" placeholder="请输入昵称" id="r_nickname">
					</div>
					<div class="mui-input-row">
						<label>电话</label>
						<input type="number" placeholder="请输入电话" id="r_mobile">
						<button>发送验证码</button>
					</div>
				</form>
				<div class="mui-button-row" style="margin: 25px auto;width: 98%;">
						<button type="button" style="padding:10px 0;height: 100%;;" class="mui-btn mui-btn-royal mui-btn-block" id="registerBtn">确认</button>&nbsp;&nbsp;
				</div>
			</div>

		</div>

		<!-- 账号与安全 -->
		<div id="account" class="mui-page">
			<div class="mui-navbar-inner mui-bar mui-bar-nav">
				<h1 class="mui-center mui-title">账号与安全</h1>
			</div>
			<div class="mui-page-content">
				<div class="mui-scroll-wrapper" style="top:50px;">
					<div class="mui-scroll">
						<ul class="mui-table-view">
							<li class="mui-table-view-cell" style="padding:15px 15px;">
								<a id="head" class="mui-navigate-right">头像
									<span class="mui-pull-right head">
										<img class="head-img mui-action-preview" id="head-img" src="./images/logo.png"/>
									</span>
								</a>
							</li>
							<li class="mui-table-view-cell">
								<a>账号<span class="mui-pull-right" id="head-username">Hbuilder</span></a>
							</li>
						</ul>
						<ul class="mui-table-view">
							<li class="mui-table-view-cell">
								<a>手机号<span class="mui-pull-right" id="head-mobile">18601234567</span></a>
							</li>
							<li class="mui-table-view-cell">
								<a>昵称<span class="mui-pull-right" id="head-nickname">hbuilder@dcloud.io</span></a>
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>

		<!-- actionsheet -->
		<div id="sheet1" class="mui-popover mui-popover-bottom mui-popover-action ">
			<!-- 可选择菜单 -->
			<ul class="mui-table-view">
			  <li class="mui-table-view-cell">
				<a href="javascript:;" id="changePhoto">更换头像</a>
				<input type="file" id="myfile" name="myfile" style="display:none">
			  </li>
			</ul>
			<!-- 取消菜单 -->
			<ul class="mui-table-view">
			  <li class="mui-table-view-cell">
				<a href="#sheet1"><b>取消</b></a>
			  </li>
			</ul>
		</div>

		<!-- 图片裁剪Panel -->
		<div id="photoclip" style="position:absolute;height:100%;width:100%;background:white;display:none;z-index:999;">
			<div id="clipArea"></div>
			<button type="button" class="mui-btn mui-btn-block mui-btn-danger" id="clipBtn">确认</button>
			<div id="view"></div>
		</div>

		<!-- 聊天对话框 -->
		<div id="chat_panel" style="display:none;">
			<div id="chat_title">
				<div class="chat_title_left">
					<img src="img/left.png" id="chat_exit" style="cursor:pointer;">
				</div>
				<div class="chat_title_center">
					杰克马
				</div>
				<div class="chat_title_right">
					资料<input type="hidden" class="_id"/>
				</div>
			</div>
			<div id="chat_content">
				<!-- <div class="content_friend">
					<img src="img/user01.jpg">
					<span>我是小Q</span>
				</div>
				<div class="content_me">
					<span>我是小A</span>
					<img src="img/user02.jpg">
				</div> -->
			</div>
			<div id="chat_bar">
				<div  id="xiaolian">
					<img src="img/xiaolian.png">
				</div>
				<input type="text" id="content">
				<div id="send">
					<button type="button" class="mui-btn mui-btn-grey" id="sendBtn">发送</button>
				</div>
			</div>
		</div>
		<audio id="ring">
			<source src="media/msg.mp3" />
		</audio>
	</body>
	<!-- MUI -->
	<script src="./js/mui.js"></script>
	<script src="./js/mui.indexedlist.js"></script>
	<!-- JQUERY -->
	<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
	<!-- CLIP -->
	<script src="js/iscroll-zoom.js"></script>
	<script src="js/hammer.js"></script>
	<script src="js/lrz.all.bundle.js"></script>
	<script src="js/jquery.photoClip.js"></script>
	<!-- Socket -->
	<script src="js/socket.io.js"></script>
	
	<script type="text/javascript">
		mui.init({
			swipeBack:true //启用右滑关闭功能
		});
	
		$('.mui-tab-item').click(switchTap);
		
		//图片裁剪插件初始化
		new bjj.PhotoClip("#clipArea", {
			size: [260, 260],
			outputSize: [640, 640],
			file: "#myfile",
			view: "#view",
			ok: "#clipBtn",
			loadStart: function() {
				console.log("照片读取中");
			},
			loadComplete: function() {
				console.log("照片读取完成");
			},
			clipFinish: function(dataURL) {
				console.log(dataURL);
				//上传头像
				upload(dataURL);
			}
		});

		window.onload=function(){
			//登录验证
			if(loginValidate()){
				loadFriends();//加载好友
				chatStart();//加载聊天程序
				loadNews();//加载消息
			}
		}


		//打开ActionSheet
		$("#head").click(function(){
			mui('#sheet1').popover('toggle');
		})

		//查找本地图像
		$("#changePhoto").click(function(){
			//打开裁剪面板
			$("#photoclip").show();
			//触发文件域点击事件
			$("#myfile").click();
			//隐藏actionsheet
			mui('#sheet1').popover('toggle');
		})

		//上传头像
		function upload(base64String){
			console.log('上传头像准备');
			//这里对base64串进行操作，去掉url头，并转换为byte
			var bytes = window.atob(base64String.split(',')[1]);
			var array = [];
			for(var i = 0; i < bytes.length; i++){
				array.push(bytes.charCodeAt(i));
			}
			var blob = new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
			var fd=new FormData();
			fd.append('myfile',blob, Date.now() + '.jpg');
			let user=getCurrentUser();
			fd.append('id',user.id);
			$.ajax({
				type:'post',
				url:'photoUpload',
				data:fd,
				contentType:false,
				processData:false,
				success:function(result){
					if(result=='no-login'){
						loginAgin(user.username,user.password);
						arguments.callee();
					}else{
						sessionStorage.setItem('user',JSON.stringify(result));
						//切换界面
						$("#account").show();
						$('.mui-content').hide();
						$("#photoclip").hide();
						//重新填充数据
						loginValidate();
					}
				},
				fail:function(err){
					console.error('图片上传失败:'+err);
				}
			})
		}

		//点击clipArea,触发文件域点击
		$("#clipArea").click(function(){
			$("#myfile").click();
		})

		//登录验证与数据填充
		function loginValidate(){
			let user=getCurrentUser();
			if(!user){
				$('#login').show().siblings().hide();
				return false;
			}
			fill(user);
			return true;
		}

		//填充个人信息
		function fill(user){
			//设置用户名
			$("#myusername").html(user.username);
			//设置昵称
			$("#mynickname").html(user.nickName);
			//设置头像
			$("#myphoto").attr("src",user.photo);
			//账户与安全
			$("#head-img").attr("src",user.photo);
			$("#head-username").html(user.username);
			$("#head-nickname").html(user.nickName);
			$("#head-mobile").html(user.mobile);
		}

		//获取当前登录用户(从sessionStorage中获取)
		function getCurrentUser(){
			let str = sessionStorage.getItem('user');
			if(str){
				return JSON.parse(str);
			}
			return null;
		}

		//从会话中获取消息列表
		function getFriendsMess(){
			let mess = sessionStorage.getItem('friends_mess');
			if(mess){
				return JSON.parse(mess);
			}
			return null;
		}

		//从会话中获取好友列表
		function getFriends(){
			let friends = sessionStorage.getItem('friends');
			if(friends){
				return JSON.parse(friends);
			}
			return null;
		}


		//显示账号与安全
		$("#showAccount").click(function(){
			$("#account").show();
			$('.mui-content').hide();
		})


		//退出登录
		$('#logout').click(function(){
			switchTap.call(this); //切换界面
			sessionStorage.removeItem('user');
		});

		//打开注册界面
		$("#signUp").click(function(){
			switchTap.call(this);
		})

		//登录
		$("#loginBtn").click(function(){
			var user=$("#l_username").val();
			var pass=$("#l_password").val();
			loginAgin(user,pass);
		})


		//注册
		$("#registerBtn").click(function(){
			var username=$("#r_username").val();
			var password=$("#r_password").val();
			var nickname=$("#r_nickname").val();
			var mobile=$("#r_mobile").val();
			ajax('post','register',{username,password,nickname,mobile},function(result){
				if(result=='success'){
					$("#login").show().siblings().hide();
					$(".page-title span").text("登录");
				}else{
					alert('后台繁忙，请稍后再试');
				}
			},function(err){
				console.error(err);
			})
		})

		function loginAgin(user,pass){
			ajax('post','login',{user,pass},function(data){
				if(data && data.length>0){
					let u =data[0];
					sessionStorage.setItem('user',JSON.stringify(u));
					// $('#login').hide();
					$("#tabbar-with-map").show().siblings().hide();
					//设置头像
					// $("#head-img").attr('src',data[0].photo);
					//设置用户名
					$("#myusername").html(u.username);
					//设置昵称
					$("#mynickname").html(u.nickName);
					loadFriends();//加载联系人
					chatStart();//加载聊天程序
					loadNews();//加载消息列表
				}else{
					alert('用户名或密码错误');
				}
			},function(err){
				console.error(err);
			})
		}

		/**
		 *  菜单切换
		 * */
		function switchTap() {
			$('.mui-content').show();
			$("#account").hide();
			var href = $(this).attr('tap');
			if(!loginValidate() && href!="register"){
				return;
			}
			$(".page-title span").text($(".mui-tab-label", $(this)).text());
			$('#' + href).show().siblings().hide();
		}
		

		//加载好友
		function loadFriends(){
			var user=getCurrentUser();
			ajax('get','friends',{"_id":user._id},function(result){
				console.log('firends:');
				if(result=='no-login'){
					loginAgin(user.username,user.password);
					arguments.callee();
				}
				console.log(result);
				$("#contact").empty();
				//通过好友信息构造出一个针对每个好友的消息列表,存储在session中
				let message={};
				// result.map(function(value){
				// 	return {
				// 		[value._id]:[]
				// 	}
				// })
				for(var value of result){
					message[value._id]=[];
				}
				sessionStorage.setItem('friends_mess',JSON.stringify(message));
				sessionStorage.setItem('friends',JSON.stringify(result));
				for(var i=0;i<result.length;i++){
					let f=result[i];
					let liStr=`
						<li class="mui-table-view-cell mui-indexed-list-item contacts">
									<!--滑动菜单-->
								<div class="mui-slider-right mui-disabled">
									<a class="mui-btn mui-btn-grey mui-icon mui-icon-person" style="transform: translate(0px, 0px);"></a>
									<a class="mui-btn mui-btn-yellow mui-icon mui-icon-phone" style="transform: translate(-90px, 0px);"></a>
									<a class="mui-btn mui-btn-red mui-icon mui-icon-email" style="transform: translate(-180px, 0px);"></a>
								</div>
								<!--列表内容-->
								<div class="mui-slider-cell mui-slider-handle" style="transform: translate(0px, 0px);">
									<div class="oa-contact-cell mui-table">
										<div class="oa-contact-avatar mui-table-cell">
											<img src="${f.photo || './img/user01.jpg'}" />
											<input type="hidden" value="${f._id}" class="_id"/>
										</div>
										<div class="oa-contact-content mui-table-cell">
											<div class="mui-clearfix">
												<h4 class="oa-contact-name">${f.nickName}</h4>
												<span class="oa-contact-position mui-h6">总经理</span>
											</div>
											<p class="oa-contact-email mui-h6">
												${f.username}
											</p>
										</div>
									</div>
								</li>
				`
			var contact = $("#contact")[0];
			contact.innerHTML += liStr;
			}
			},function(err){
				console.log('error:');
				console.log(err);
			});
		}



		//加载消息
		function loadNews(){
			var user=getCurrentUser();
			var message=getFriendsMess();
			var friends = getFriends();
			if(!message || !friends){
				return;
			}
			for(var f in message){
					//取出消息列表中的每个人的ID,到好友列表中查找详细信息
					for(var i=0;i<friends.length;i++){
						var friend=friends[i];
						if(friend._id==f && message[f].length>0){
							let mess=message[f][message[f].length-1];//取出当前联系人的最新一条消息(可能是自己发的,也可能是对方发的)
							var liStr=`
									<li class="mui-table-view-cell mui-indexed-list-item messages">
												<!--滑动菜单-->
											<div class="mui-slider-right mui-disabled">
												<a class="mui-btn mui-btn-red" style="transform: translate(0px, 0px);">删除</a>
											</div>
											<!--列表内容-->
											<div class="mui-slider-cell mui-slider-handle" style="transform: translate(0px, 0px);">
												<div class="oa-contact-cell mui-table">
													<div class="oa-contact-avatar mui-table-cell">
														<img src="${friend.photo || './img/user01.jpg'}" />
														<input type="hidden" value="${friend._id}" class="_id"/>
													</div>
													<div class="oa-contact-content mui-table-cell">
														<div class="mui-clearfix">
															<h4 class="oa-contact-name">${friend.nickName}</h4>
														</div>
														<p class="oa-contact-email mui-h6">
															${mess.friend || mess.me}
														</p>
													</div>
												</div>
											</li>
									`;
							console.log($(`input[value='${friend._id}']`).parents('.messages'));
							$(`input[value='${friend._id}']`).parents('.messages').remove();
							var messageList = $("#messageList")[0];
							messageList.innerHTML += liStr;
							break;//匹配到联系人之后,内层循环停止，继续查找下个好友ID对应的联系人
						}
					}
			}
		}
		


		//Ajax
		function ajax(type,url,data,success,fail){
			$.ajax({
				type:type,
				url:url,
				data,
				async:true,
				success,fail
			});
		}
	</script>

	<script>

		//点击联系人,打开聊天窗口
		$(document).on('click','.contacts,.messages',function(){
			//获取对方信息(昵称,ID)
			let _id = $("._id",this).val();
			//获取对方昵称
			let nickname=$(".oa-contact-name",this).html();
			//将好友的昵称显示在聊天窗口的顶部
			$(".chat_title_center").html(nickname);
			//将好友的ID存储在当前聊天窗的隐藏域中
			$("#chat_panel ._id").val(_id);
			//显示聊天窗口
			$("#chat_panel").show();
			//打开聊天窗口,文本框自动获得焦点
			$("#content")[0].focus();
			//从消息列表中取出与此位好友的聊天内容
			var photo=$("img",this).attr('src');
			currentFriendPhoto=photo;
			currentFriendId=_id;
			getNews(_id,photo);
			//清除未读数量标记
			$("#badge").html("").hide();
		})

		let currentFriendPhoto=null;//当前的聊天对象
		let currentFriendId=null;

		function getNews(_id,photo){
			var message = getFriendsMess();
			if(!message){
				return;
			}
			var user=getCurrentUser();
			$("#chat_content").empty();
			// for(var f of message){
				if(message[_id]){
					var arr=message[_id];
					for(var obj of arr){
						if(obj.hasOwnProperty('me')){
							var chat=`
								<div class="content_me">
									<span>${obj.me}</span>
									<img src="${user.photo}">
								</div>
								`;
						}else if(obj.hasOwnProperty('friend')){
							var chat=`
								<div class="content_friend">
									<img src="${photo}">
									<span>${obj.friend}</span>
								</div>
								`;
						}
						$("#chat_content").append($(chat));
					}
				}
			// }
		}

		//点击箭头,关闭聊天窗口
		$("#chat_exit").click(function(){
			$("#chat_panel").hide();
		})


		let socket=null;

		//启动通信
		function chatStart(){
			let user=getCurrentUser();
			socket = io.connect('http://127.0.0.1:9000');
			//登入（将当前用户的userid存储在后台的在线列表中）
			socket.emit('sign',user)
			//接收他人消息
			socket.on('STC',function(arr){
				for(let i=0;i<arr.length;i++){
					var obj=arr[i];
					var friend_id=obj.friend || obj.from;
					console.log('好友:'+friend_id+'发来消息：'+obj.message);
					//将收集到的消息根据好友ID分别在存储在消息集合中
					let message=getFriendsMess();
					// message.map(function(value){
						message[friend_id].push({"friend":obj.message});
					// })
					sessionStorage.setItem('friends_mess',JSON.stringify(message));
					//显示在聊天窗中
					if(currentFriendId==friend_id){
						var chat=`
							<div class="content_friend">
								<img src="${currentFriendPhoto}">
								<span>${obj.message}</span>
							</div>
						`;
						$("#chat_content").append($(chat));
					}
				}
				loadNews();//显示消息列表
				//底部菜单未读消息数量标注(聊天窗口没有打开的情况下才显示未读消息数量)
				if(arr.length>0 && $("#chat_panel").is(':hidden')){
					$("#badge").html(arr.length).show();
					ring.play();
				}
			})
		}

		//根据文本框输入的内容改变发送按钮的样式
		$("#content").keyup(function(e){
			if(this.value.trim()!=""){
				$("#sendBtn").removeClass('mui-btn-grey').addClass('mui-btn-warning').prop('disabled',false);
				if(e.keyCode==13){
					sendMessage();
				}
			}else{
				$("#sendBtn").removeClass('mui-btn-warning').addClass('mui-btn-grey').prop('disabled',true);
			}
		})

		$("#sendBtn").click(sendMessage);
		
		//发送消息(点击回车 or  点击 发送按钮)
		function sendMessage(){
			var user=getCurrentUser();
			console.log($("#content").val());
			var chat=`
					<div class="content_me">
						<span>${$("#content").val()}</span>
						<img src="${user.photo}">
					</div>
					`;
			$("#chat_content").append($(chat));
			//将自己发的消息也要存储在消息列表中(sessionStorage)
			let message=getFriendsMess();

			// message.map(function(value){
				message[$("#chat_panel ._id").val()].push({"me":$("#content").val()});
			// })
			sessionStorage.setItem('friends_mess',JSON.stringify(message));
			//发送给服务器
			socket.emit('CTS',{
				friend:$("#chat_panel ._id").val(),
				message:$("#content").val()
			})
			//清空文本框
			$("#content").val("");
			//改变按钮样式
			$("#sendBtn").removeClass('mui-btn-warning').addClass('mui-btn-grey').prop('disabled',true);
		}

	</script>
</html>